<?php

namespace App\Http\Controllers\Admin\Finance\Payable;

use App\Http\Controllers\Admin\Base\ExchangeRate;
use App\Http\Controllers\Controller;
use App\Http\Requests\airline\base\BanRequest;
use App\Models\airline\base\FlightModel as BaseFlightModel;
use App\Models\base\CurrencyModel;
use App\Models\DictionaryModel;
use App\Models\finance\PayableTakeOrderDetailModel;
use App\Models\finance\PayableTakeOrderModel;
use App\Models\finance\PayableTmpModel;
use App\Models\OrderModel;
use App\Models\TakeOrderModel;
use App\Models\TakeOrderRecModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TakeOrder extends Controller
{
    use BanRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $take_order_sn = $request->input('take_order_sn', '');
        $start_date = $request->input('start_date', '');
        $end_date = $request->input('end_date', '');
        $check_type = $request->input('check_type', '');
        $operator = $request->input('operator', '');
        $servicer = $request->input('servicer', '');
        $customer_id = $request->input('customer_id', '');
        $start_port_code = $request->input('origin', '');
        $arrive_port_code = $request->input('destination', '');
        $master = $request->input('master', '');
        $airline_flight_id = $request->input('airline_flight_id', '');
        $route_id = $request->input('route_id', '');
        $air_company_id = $request->input('air_company_id', '');


        $query = PayableTakeOrderModel::query()->with(['take_order', 'flight', 'tmp', 'customer'])->whereHas('customer', function($query) {
            $query->where('is_big', 0);
        });

        if($take_order_sn){
//            $find = TakeOrderModel::query()->where('sn', $take_order_sn)->first();
//            $take_order_id = $find->id ?? 0;
//            $query->where('take_order_id', $take_order_id);

            $query->whereHas('take_order', function($query) use ($take_order_sn) {
                $query->where('sn', 'like', '%' . $take_order_sn . '%');
            });
        }

        if($check_type && $start_date && $end_date){
            if($check_type == 1){
                $query->whereBetween('flight_date', [$start_date, $end_date]);
            }
            if($check_type == 2){
                $query->whereBetween('created_at', [$start_date . ' 00:00:00', $end_date . ' 23:59:59']);
            }
        }

        if($operator){
            $query->where('operator', $operator);
        }

        if($servicer){
            $query->where('servicer', $servicer);
        }

        if($customer_id){
            $query->where('customer_id', $customer_id);
        }

        if($start_port_code || $arrive_port_code || $route_id || $airline_flight_id || $air_company_id){
            $query->whereHas('flight', function($query) use ($start_port_code, $arrive_port_code, $route_id, $airline_flight_id, $air_company_id) {
                if($start_port_code){
                    $query->where('start_port_code', $start_port_code);
                }
                if($arrive_port_code){
                    $query->where('arrive_port_code', $arrive_port_code);
                }
                $query->whereHas('items', function($query) use ($route_id, $airline_flight_id, $air_company_id) {
                    if($route_id){
                        $query->where('route_id', $route_id);
                    }
                    if($airline_flight_id){
                        $query->where('airline_flight_id', $airline_flight_id);
                    }
                    if($air_company_id){
                        $query->where('airline_company_id', $air_company_id);
                    }
                });
            });
        }

        if($master){
            $query->where('master', $master);
        }


        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $flight_date = $item->flight ? date('Y-m-d', strtotime($item->flight->take_off_time)) : '';
            //航班号
            $airline_flight_ids = $item->flight?->items?->pluck('airline_flight_id') ?? [];
            $flight_number = BaseFlightModel::whereIn('id', $airline_flight_ids)->pluck('flight_number')->toArray();

            $res = [
                'id' => $item->id,
                'take_order_id' => $item->take_order_id,
                'flight_date' => $flight_date,
                'sn' => $item->take_order->sn ?? '',
                'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->goods_attr] ?? '',
                'take_warehouse' => $item->take_order->take_warehouse ?? '',
                'master' => $item->take_order->master ?? '',
                'start_port_code' => $item->flight->start_port_code ?? '',
                'arrive_port_code' => $item->flight->arrive_port_code ?? '',
                'big_pkgs' => $item->big_pkgs,
                'volume_weight' => $item->take_order->volume_weight,
                'reality_weight' => $item->take_order->reality_weight,
                'servicer' => $item->take_order->servicer ?? '',
                'operator' => $item->take_order->operator ?? '',
                'flight_number' => implode(',', $flight_number),
                'hk_land' => TakeOrderModel::HK_LAND_MAPS[$item->take_order->hk_land] ?? '',
                'hk_provide' => TakeOrderModel::HK_PROVIDE_MAPS[$item->take_order->hk_provide] ?? '',
                'tmp_id' => $item->tmp_id,
                'tmp_name' => $item->tmp->name ?? '',
                'amount' => $item->amount,
                'amount_cny' => $item->amount_cny,
                'confirm_status' => $item->confirm_status,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }


    public function template_import(Request $request) {
        $id = $request->input('id',  '');
        $tmp_id = $request->input('tmp_id',  '');

        $payable_take_order = PayableTakeOrderModel::find($id);
        if(!$payable_take_order) {
            return $this->error('提单不存在');
        }

        $tmp_find = PayableTmpModel::find($tmp_id);
        if(!$tmp_find){
            return $this->error('模板不存在');
        }

        $tmp_detail = $tmp_find->detail;
        $weight = $payable_take_order->reality_weight;

        $rate_cny = (new ExchangeRate())->cny_rate();

//        DB::beginTransaction();
//        try{
//            $payable_take_order->tmp_id = $tmp_id;
//            $payable_take_order->save();

            $detail_insert = []; $amount_total = $amount_cny_total = 0;
            foreach ($tmp_detail as $item){

                $rate_error = [];
                if(!isset($rate_cny[$item['currency_id']])){
                    $find_currency = CurrencyModel::find($item['currency_id']);
                    $find_currency_name = $find_currency->name ?? '';
                    $rate_error[] = $find_currency_name . '汇率不存在';
                    break;
                }

                $rate = $rate_cny[$item['currency_id']]['rate'];

                $number = $item['number'] == 0 ? $weight : 1;
                $amount = round($item['price'] * $number, 4);
                $amount_cny = round($amount * $rate, 4);

//                $amount_total += $amount;
//                $amount_cny_total += $amount_cny;

                $detail_insert[] = [
//                    'payable_take_order_id' => $id,
//                    'take_order_id' => $payable_take_order->take_order_id,
                    'agent_id' => $item['agent_id'],
                    'name' => $item['name'],
                    'number' => $number,
                    'unit' => $item['unit'],
                    'price' => $item['price'],
                    'currency_id' => $item['currency_id'],
                    'rate' => $rate,
                    'amount' => $item['price'] * $number,
                    'amount_cny' => $amount_cny,
                    'flight_date' => $payable_take_order->flight_date,
                ];
            }


            if($rate_error){
                return $this->error('请先添加汇率：' . implode(',', $rate_error));
            }

//            PayableTakeOrderDetailModel::insert($detail_insert);
//
//            $payable_take_order->amount = $amount_total;
//            $payable_take_order->amount_cny = $amount_cny_total;
//            $payable_take_order->save();
//
//            DB::commit();
//        } catch(\Exception $e) {
//            DB::rollBack();
//            return $this->error($e->getMessage());
//        }

        return $this->success(['list' => $detail_insert]);

    }

    public function detail_confirm(Request $request) {
        $id = $request->input('id');
        $tmp_id = $request->input('tmp_id',  '');
        $detail = $request->input('detail',  []);

        $payable_take_order = PayableTakeOrderModel::find($id);

        if(!$detail){
            return $this->error('请添加明细');
        }

        $total_amount = 0;
        foreach ($detail as &$item){
            $item['payable_take_order_id'] = $id;
            $item['take_order_id'] = $payable_take_order->take_order_id;
            $item['flight_date'] = $payable_take_order->flight_date;
            $total_amount += $item['amount_cny'] ?? 0;
        }

        DB::beginTransaction();
        try{

            PayableTakeOrderDetailModel::insert($detail);

            if($tmp_id){
                $payable_take_order->tmp_id = $tmp_id;
            }
            $payable_take_order->amount_cny = $total_amount;
            $payable_take_order->confirm_status = 1;
            $payable_take_order->save();

            DB::commit();
        } catch(\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();

    }


    public function detail(Request $request) {
        $id = $request->input('id');

        $take_order = PayableTakeOrderModel::find($id);
        if(!$take_order) {
            return $this->error('提单不存在');
        }

        $detail = PayableTakeOrderDetailModel::with(['agent', 'currency'])->where('payable_take_order_id', $id)->get();

        $list = $detail->map(function($item) {
            $res = [
                'id' => $item->id,
//                'payable_take_order_id' => $item->payable_take_order_id,
//                'take_order_id' => $item->take_order_id,
//                'agent_id' => $item->agent_id,
                'agent_name' => $item->agent->name ?? '',
                'name' => $item->name,
                'number' => $item->number,
                'unit' => $item->unit,
                'price' => $item->price,
//                'currency_id' => $item->currency_id,
                'currency_code' => $item->currency->short_code ?? '',
                'rate' => $item->rate,
                'amount' => $item->amount,
                'amount_cny' => $item->amount_cny,
            ];
            return $res;
        });

        $list = $list->toArray() ?? [];

        $amount_total = $detail->sum('amount') ?? 0;
        $amount_total_cny = $detail->sum('amount_cny') ?? 0;
        $total = [
            'amount' => $amount_total,
            'amount_cny' => $amount_total_cny,
        ];

        return $this->success(['list' => $list, 'total' => $total]);
    }


    public function detail2(Request $request) {
        $id = $request->input('id');
        $take_order_id = $request->input('take_order_id');
        $take_order = TakeOrderModel::find($take_order_id);
        if(!$take_order) {
            return $this->error('提单不存在');
        }

        $payable_take_order = PayableTakeOrderModel::find($id);
        if(!$payable_take_order) {
            return $this->error('参数错误');
        }

        $detail = PayableTakeOrderDetailModel::with(['agent', 'currency'])->where('payable_take_order_id', $id)->get();

        $list = $detail->map(function($item) {
            $res = [
                'id' => $item->id,
//                'payable_take_order_id' => $item->payable_take_order_id,
//                'take_order_id' => $item->take_order_id,
                'agent_id' => $item->agent_id,
                'agent_name' => $item->agent->name ?? '',
                'name' => $item->name,
                'number' => $item->number,
                'unit' => $item->unit,
                'price' => $item->price,
                'currency_id' => $item->currency_id,
                'currency_code' => $item->currency->short_code ?? '',
                'rate' => $item->rate,
                'amount' => $item->amount,
                'amount_cny' => $item->amount_cny,
            ];
            return $res;
        });

        $list = $list->toArray() ?? [];

//        $storage_volume = $take_order->orders->sum('storage_volume');


        //详情
//        $detail = [
//            'customer_name' => $take_order->customer->name ?? '',
//            'customer_sn' => $take_order->customer->sn ?? '',
//            'customer_type' => $take_order->customer->customer_type->name ?? '',
//            'sn' => $take_order->sn,
//            'status_name' => TakeOrderModel::STATUS_MAPS[$take_order->status] ?? '',
//            'storage_volume' => $storage_volume,
//            'storage_weight' => $take_order->orders->sum('storage_weight'),
//            'take_off_time' => $take_order->flight->take_off_time ?? '',
//            'created_at' => $take_order->created_at->toDateTimeString(),
//        ];

//        //入仓单
//        $orders = $take_order->orders->map(function($order) {
//            $packages_name = DictionaryModel::whereIn('id', explode(',', $order->packages))
//                ->pluck('name');
//            return [
//                'id' => $order->id,
//                'sn' => $order->sn,
//                'big_pkgs' => $order->big_pkgs,
//                'pre_out_date' => $order->pre_out_date,
//                'des_country_name' => $order->airport->country_name ?? '',
//                'goods_attr_name' => OrderModel::GOODS_ATTR_MAPS[$order->goods_attr] ?? '',
//                'clearance_mode_name' => OrderModel::CLEARANCE_MODE_MAPS[$order->clearance_mode] ?? '',
//                'is_clearance' => $order->is_clearance,
//                'pre_volume' => $order->pre_volume,
//                'storage_weight' => $order->storage_weight,
//                'packages_name' => $packages_name,
//                'storage_time' => $order->storage_time,
//            ];
//        });

        $master = $take_order->master;
        if(empty($master)) {
            $master = $take_order->flight->carrier;
        }

        //完善资料
        $perfect = [
            'operator' => $take_order->operator,
            'servicer' => $take_order->servicer,
            'shipment_date' => $take_order->shipment_date,
            'cca' => $take_order->cca,
            'take_warehouse' => $take_order->take_warehouse,
            'master' => $master,
            'slipt_order_count' => $take_order->slipt_order_count,
            'clr_agent_id' => $take_order->clr_agent_id,
            'clr_agent_name' => $take_order->clr_agent->name ?? '',
            'dec_type' => $take_order->dec_type,
            'dec_type_name' => TakeOrderModel::DEC_TYPE_MAPS[$take_order->dec_type] ?? '',
            'dec_method' => $take_order->dec_method,
            'dec_method_name' => TakeOrderModel::DEC_METHOD_MAPS[$take_order->dec_method] ?? '',
            'dec_agent_id' => $take_order->dec_agent_id,
            'dec_agent_name' => $take_order->dec_agent->name ?? '',
            'fake_brand' => $take_order->fake_brand,
            'origin_ledger' => $take_order->origin_ledger,
            'mix_tick' => $take_order->mix_tick,
            'dec_incidentals' => $take_order->dec_incidentals,
            'dec_incidentals_remark' => $take_order->dec_incidentals_remark,
            'separate_dec_weight' => $take_order->separate_dec_weight,
            'separate_dec_volume' => $take_order->separate_dec_volume,
            'separate_dec_page_fee' => $take_order->separate_dec_page_fee,
            'hk_land' => $take_order->hk_land,
            'hk_land_remark' => $take_order->hk_land_remark,
            'hk_provide' => $take_order->hk_provide,
            'hk_provide_remark' => $take_order->hk_provide_remark,
            'bj_3' => $take_order->bj_3,
            'bj_3_remark' => $take_order->bj_3_remark,
            'bj_8' => $take_order->bj_8,
            'bj_8_remark' => $take_order->bj_8_remark,
            'remark' => $take_order->remark,
            'separate_dec' => $take_order->orders->map(function($order) {
                return [
                    'id' => $order->id,
                    'sn' => $order->sn,
                    'separate_dec_weight' => $order->separate_dec_weight,
                    'separate_dec_volume' => $order->separate_dec_volume,
                    'separate_dec_page_fee' => $order->separate_dec_page_fee,
                    'separate_dec_method' => $order->separate_dec_method,
                    'separate_dec_other' => $order->separate_dec_other,

                ];
            }),
            'hk_take' => $take_order->orders->map(function($order) {
                return [
                    'id' => $order->id,
                    'sn' => $order->sn,
                    'weight' => $order->hk_take_weight,
                    'hk_take_fee' => $order->hk_take_fee,
                    'hk_take_sign_fee' => $order->hk_take_sign_fee,
                    'hk_take_park_fee' => $order->hk_take_park_fee,
                    'hk_take_remark' => $order->hk_take_remark,
                ];
            }),
            'hk_zs' => $take_order->orders->map(function($order){
                return [
                    'id' => $order->id,
                    'sn' => $order->sn,
                    'hk_zs_weight' => $order->hk_zs_weight,
                    'hk_zs_sign_fee' => $order->hk_zs_sign_fee,
                    'hk_zs_park_fee' => $order->hk_zs_park_fee,
                    'hk_zs_remark' => $order->hk_zs_remark,
                ];
            }),
            'wf' => $take_order->wf->map(function($item) {
                return [
                    'id' => $item->id,
                    'sn' => $item->order->sn,
                    'multi_pack_nums' => $item->multi_pack_nums,
                    'multi_pack_weight' => $item->multi_pack_weight,
                    'multi_pack_price' => $item->multi_pack_price,
                    'carton_hm_nums' => $item->carton_hm_nums,
                    'carton_hm_price' => $item->carton_hm_price,
                    'put_express_nums' => $item->put_express_nums,
                    'put_express_price' => $item->put_express_price,
                    "dbc_nums" => $item->dbc_nums,
                    "dbc_price" => $item->dbc_price,
                    "yx_unload_weight" => $item->yx_unload_weight,
                    "yx_unload_price" => $item->yx_unload_price,
                    "sd_price" => $item->sd_price,
                    "ztc_price" => $item->ztc_price,
                    "ztc_after" => $item->ztc_after,
                ];
            }),
            'special' => $take_order->special->map(function($item) {
                return [
                    "id" => $item->id,
                    "take_order_id" => $item->take_order_id,
                    "price" => $item->price,
                    "weight" => $item->weight,
                    "type" => $item->type,
                    'amount' => $item->amount,
                ];
            })
        ];


        return $this->success([
            'detail' => $list,
            'perfect' => $perfect,
        ]);

    }



}
